using System;
using System.Drawing;
using System.IO;

namespace SnakeGame
{
    /// <summary>
    /// 游戏控制器类
    /// </summary>
    public class GameController
    {
        public Snake Snake { get; private set; }
        public Food Food { get; private set; }
        public GameState State { get; private set; }
        public GameConfig Config { get; private set; }
        public GameDifficulty Difficulty { get; private set; }

        // 计分相关
        public int CurrentScore { get; private set; }
        public int HighScore { get; private set; }
        public int ConsecutiveFoods { get; private set; }

        // 排行榜
        public Leaderboard Leaderboard { get; private set; }

        // 事件
        public event EventHandler GameStateChanged;
        public event EventHandler ScoreChanged;
        public event EventHandler GameOver;

        private readonly string highScoreFile = "highscore.txt";

        public GameController()
        {
            Snake = new Snake();
            Food = new Food();
            State = GameState.NotStarted;
            Difficulty = GameDifficulty.Medium;
            Config = GameConfig.GetConfigByDifficulty(Difficulty);
            CurrentScore = 0;
            ConsecutiveFoods = 0;
            Leaderboard = new Leaderboard();
            LoadHighScore();
        }

        /// <summary>
        /// 开始新游戏
        /// </summary>
        public void StartGame()
        {
            Snake = new Snake();
            Food = new Food();
            State = GameState.Playing;
            CurrentScore = 0;
            ConsecutiveFoods = 0;
            Food.Generate(Config.GameWidth, Config.GameHeight, Snake.Body);
            OnGameStateChanged();
        }

        /// <summary>
        /// 暂停游戏
        /// </summary>
        public void PauseGame()
        {
            if (State == GameState.Playing)
            {
                State = GameState.Paused;
                OnGameStateChanged();
            }
        }

        /// <summary>
        /// 继续游戏
        /// </summary>
        public void ResumeGame()
        {
            if (State == GameState.Paused)
            {
                State = GameState.Playing;
                OnGameStateChanged();
            }
        }

        /// <summary>
        /// 重新开始游戏
        /// </summary>
        public void RestartGame()
        {
            StartGame();
        }

        /// <summary>
        /// 设置游戏难度
        /// </summary>
        public void SetDifficulty(GameDifficulty difficulty)
        {
            Difficulty = difficulty;
            Config = GameConfig.GetConfigByDifficulty(difficulty);
        }

        /// <summary>
        /// 更新游戏状态
        /// </summary>
        public void Update()
        {
            if (State != GameState.Playing)
                return;

            // 移动蛇
            Snake.Move();

            // 检查碰撞
            if (CheckCollisions())
            {
                EndGame();
                return;
            }

            // 检查是否吃到食物
            if (Snake.IsEatingFood(Food.Position))
            {
                EatFood();
            }
        }

        /// <summary>
        /// 检查碰撞
        /// </summary>
        private bool CheckCollisions()
        {
            // 检查是否撞墙
            if (Snake.IsCollidingWithWall(Config.GameWidth, Config.GameHeight))
                return true;

            // 检查是否撞到自己
            if (Snake.IsCollidingWithSelf())
                return true;

            return false;
        }

        /// <summary>
        /// 吃到食物
        /// </summary>
        private void EatFood()
        {
            // 增长蛇身
            Snake.Grow();

            // 计算得分
            CalculateScore();

            // 生成新食物
            Food.Generate(Config.GameWidth, Config.GameHeight, Snake.Body);

            // 增加连续吃食物计数
            ConsecutiveFoods++;

            OnScoreChanged();
        }

        /// <summary>
        /// 计算得分
        /// </summary>
        private void CalculateScore()
        {
            int baseScore = 10;
            CurrentScore += baseScore;

            // 连续吃食物奖励
            if (ConsecutiveFoods >= 3)
            {
                CurrentScore += 5;
                ConsecutiveFoods = 0; // 重置连续计数
            }
        }

        /// <summary>
        /// 结束游戏
        /// </summary>
        private void EndGame()
        {
            State = GameState.GameOver;
            
            // 更新最高分
            if (CurrentScore > HighScore)
            {
                HighScore = CurrentScore;
                SaveHighScore();
            }

            OnGameStateChanged();
            OnGameOver();
        }

        /// <summary>
        /// 改变蛇的方向
        /// </summary>
        public void ChangeSnakeDirection(Direction direction)
        {
            if (State == GameState.Playing)
            {
                Snake.ChangeDirection(direction);
            }
        }

        /// <summary>
        /// 加载最高分
        /// </summary>
        private void LoadHighScore()
        {
            try
            {
                if (File.Exists(highScoreFile))
                {
                    string scoreText = File.ReadAllText(highScoreFile);
                    if (int.TryParse(scoreText, out int score))
                    {
                        HighScore = score;
                    }
                }
            }
            catch (Exception)
            {
                HighScore = 0;
            }
        }

        /// <summary>
        /// 保存最高分
        /// </summary>
        private void SaveHighScore()
        {
            try
            {
                File.WriteAllText(highScoreFile, HighScore.ToString());
            }
            catch (Exception)
            {
                // 保存失败时不抛出异常
            }
        }

        /// <summary>
        /// 获取游戏区域大小
        /// </summary>
        public Size GetGameAreaSize()
        {
            return new Size(Config.GameWidth * Config.CellSize, Config.GameHeight * Config.CellSize);
        }

        /// <summary>
        /// 获取游戏状态文本
        /// </summary>
        public string GetGameStateText()
        {
            switch (State)
            {
                case GameState.NotStarted:
                    return "游戏未开始";
                case GameState.Playing:
                    return "游戏中";
                case GameState.Paused:
                    return "游戏暂停";
                case GameState.GameOver:
                    return "游戏结束";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 检查分数是否足够进入排行榜
        /// </summary>
        public bool IsScoreQualifiedForLeaderboard()
        {
            return Leaderboard.IsScoreQualified(CurrentScore);
        }

        /// <summary>
        /// 添加分数到排行榜
        /// </summary>
        public void AddScoreToLeaderboard(string playerName)
        {
            // 0分不进入排行榜
            if (CurrentScore <= 0)
                return;
                
            if (IsScoreQualifiedForLeaderboard())
            {
                Leaderboard.AddEntry(playerName, CurrentScore, Difficulty);
            }
        }

        // 事件触发方法
        protected virtual void OnGameStateChanged()
        {
            GameStateChanged?.Invoke(this, EventArgs.Empty);
        }

        protected virtual void OnScoreChanged()
        {
            ScoreChanged?.Invoke(this, EventArgs.Empty);
        }

        protected virtual void OnGameOver()
        {
            GameOver?.Invoke(this, EventArgs.Empty);
        }
    }
} 